# coding: utf-8
from _imaging import path
__author__ = 'shiyongqin'
import base64
import os
def file_to_base64(inpath):
    """
    对图片内容base64编码
    :param path: 文件路径
    :return: BASE64编码后的文件内容
    """
    f, after_base64 = None, None
    try:
        f = open(inpath, 'rb')  # 二进制方式打开图文件
        after_base64 = base64.b64encode(f.read())  # 读取文件内容，转换为base64编码
    except Exception as ex:
        print ex.message
    finally:
        if f:
            f.close()
    return after_base64

def base64_to_file(outpath, imgBase64):
    """
    对base编码数据进行解码，并保存文件
    :param outpath: 文件保存路径，
    :return: BASE64编码后的文件内容
    """
    try:
        # img解码
        imgData = base64.b64decode(imgBase64)
        pathElement = os.path.split(outpath)
        s = str(pathElement[0])
        # 目录录不存在则创建目录
        if not os.path.exists(s):
            os.makedirs(s)
        # 存储图片
        file = open(outpath, 'wb')
        file.write(imgData)
        file.close()
        print 'success'
    except Exception, e:
        print e.message


if __name__ == '__main__':
    #1.对文件进行base64编码
    inpath="%s\\test_1.png" % os.path.dirname(os.path.realpath(__file__))
    imgBase64=img_to_64(inpath)
    print imgBase64
    #2.对base64编码数据进行解码
    outpath="%s\\handle.png" % os.path.dirname(os.path.realpath(__file__))
    storePic(outpath,imgBase64)

